from rest_framework import serializers
from django.utils.timezone import now,timedelta
from django.db import transaction

from .models import MovieOrders,TicketSeat
from movies.models import FilmSchedule,MovieDetail,MovieHall,MovieTypeCategory


class MovieOrdersSerializer(serializers.ModelSerializer):

    class Meta:
        model = MovieOrders
        fields = "__all__"

class TicketSeatSerializer(serializers.ModelSerializer):
    class Meta:
        model = TicketSeat
        fields = "__all__"

class MovieOrdersCreateSerializer(serializers.ModelSerializer):
    price = serializers.HiddenField(default=0)
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    film_schedule = serializers.HiddenField(default="")

    def create(self, validated_data):

        #django的事务逻辑
        with transaction.atomic():
            first_film_schedule = None
            for i in validated_data['seats']:


                #判断片场是否都一致
                if not first_film_schedule:
                    first_film_schedule = i.film_schedule
                else:
                    if first_film_schedule.id != i.film_schedule.id:
                        raise serializers.ValidationError(
                            '所有的订座必须在一个片场之内'
                        )

                validated_data['price'] += i.film_schedule.price
                validated_data['film_schedule'] = i.film_schedule
                status = i.status

                # if str(status) == "2":
                #     raise serializers.ValidationError(
                #         '{}:行{}:列的座位已经被够买'.format(
                #             i.movie_hall_seat.row,i.movie_hall_seat.col,
                #         )
                #     )
                #
                # if str(status) == "3":
                #     if i.lock_time >= now():
                #
                #         raise serializers.ValidationError(
                #             '{}:行{}:列的座位已经被锁定'.format(
                #                 i.movie_hall_seat.row,i.movie_hall_seat.col,
                #             )
                #         )
                i.status = "3"
                i.lock_time = now() + timedelta(minutes=20)
                i.save()

        ## mysql commit

        return super().create(validated_data)

    class Meta:
        model = MovieOrders
        fields = ("price","seats",'user','film_schedule')


class MovieForFilmScheduleSerializer(serializers.ModelSerializer):
    model = MovieDetail
    fields = ("name",)
class MovieHallForFilmScheduleSerializer(serializers.ModelSerializer):
    model = MovieHall
    fields = ("name",)
class KindForFilmScheduleSerializer(serializers.ModelSerializer):
    model = MovieTypeCategory
    fields = ("name",)

class FilmScheduleSerializer(serializers.ModelSerializer):
    # 序列化里面的嵌套循环 如果是对多对模型就需要设置 many=True,read_only=True一般要写上
    movie_hall = MovieHallForFilmScheduleSerializer(read_only=True)
    movie = MovieForFilmScheduleSerializer(read_only=True)
    kind = KindForFilmScheduleSerializer(read_only=True)
    class Meta:
        model = FilmSchedule
        fields = ("start_time",'end_time','movie_hall','movie','kind')
"""
1. MYSQL事务

2. 

    A: 30000    向b转账 1000
    
    B: 2000     b收到  1000
    
    mysql --->start 
    
    1. A --> update A money set 29000 
    
  
    
    2. B --> update B money set 3000 
    
    mysql --- commit
    
"""